package com.aizhixin.lab.course.course.service;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.course.classes.service.CourseClassService;
import com.aizhixin.lab.course.course.dto.ChapterImagesDTO;
import com.aizhixin.lab.course.course.entity.*;
import com.aizhixin.lab.course.course.repository.*;
import com.aizhixin.lab.course.template.entity.*;
import com.aizhixin.lab.course.template.repository.*;
import com.aizhixin.lab.docker.entity.ChapterImages;
import com.aizhixin.lab.docker.repository.ChapterImagesRepository;
import com.aizhixin.lab.remote.RDSClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
@Service
@Transactional
public class CourseTemplateService {
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private CourseFileRepository courseFileRepository;
    @Autowired
    private CourseProfRepository courseProfRepository;
    @Autowired
    private CourseChapterRepository courseChapterRepository;
    @Autowired
    private CourseChapterFileRepository courseChapterFileRepository;
    @Autowired
    private CourseAssistRepository courseAssistRepository;
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private TemplateFileRepository templateFileRepository;
    @Autowired
    private TemplateProfRepository templateProfRepository;
    @Autowired
    private TemplateChapterRepository templateChapterRepository;
    @Autowired
    private TemplateChapterFileRepository templateChapterFileRepository;
    @Autowired
    private TemplateAssistRepository templateAssistRepository;
    @Autowired
    private RDSClient rdsClient;
    @Autowired
    private ChapterImagesRepository chapterImagesRepository;

    public Map<String, Object> createCourse(String token, Long userId, Long templateId) {
        Map<String, Object> result = new HashMap<>();
        Template template = templateRepository.findByIdAndDeleteFlag(templateId, DataValidity.VALID.getState());
        if (template != null) {
            String courseId = UUID.randomUUID().toString();
            copyTemplate2Course(token, userId, template, courseId);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "没有课程信息");
        }
        return result;
    }

    private void copyTemplate2Course(String token, Long userId, Template template, String courseId) {
        //course
        Course course = new Course();
        BeanUtils.copyProperties(template, course);
        course.setId(courseId);
        course.setIsPublish(false);
        course.setIsArchive(false);
        course.setTemplateId(template.getId());
        course.setCreatedBy(userId);
        course.setCreatedDate(new Date());
        course.setLastModifiedDate(new Date());
        course.setViewCountChapter(course.getCountChapter());
        course.setViewCountSection(course.getCountSection());
        course = courseRepository.save(course);
        //course prof
        List<TemplateProf> templateProfs = templateProfRepository.findByTemplateId(template.getId());
        if (!templateProfs.isEmpty()) {
            List<CourseProf> courseProfs = new ArrayList<>();
            for (TemplateProf prof : templateProfs) {
                CourseProf courseProf = new CourseProf();
                BeanUtils.copyProperties(prof, courseProf);
                courseProf.setId(null);
                courseProf.setCourseId(course.getId());
                courseProfs.add(courseProf);
            }
            courseProfRepository.save(courseProfs);
        }
        //course file
        List<TemplateFile> templateFiles = templateFileRepository.findByTemplateId(template.getId());
        if (!templateFiles.isEmpty()) {
            List<CourseFile> courseFiles = new ArrayList<>();
            for (TemplateFile file : templateFiles) {
                CourseFile courseFile = new CourseFile();
                BeanUtils.copyProperties(file, courseFile);
                courseFile.setId(null);
                courseFile.setCourseId(course.getId());
                courseFile.setIsHide(false);
                courseFiles.add(courseFile);
            }
            courseFileRepository.save(courseFiles);
        }
        //course chapter
        List<TemplateChapter> templateChapters = templateChapterRepository.findByTemplateIdAndParentIdIsNullOrderByOrderNo(template.getId());
        saveCourseChapters(token, userId.toString(), course.getId(), null, templateChapters);
        //course assist
        List<TemplateAssist> templateAssists = templateAssistRepository.findByTemplateIdAndParentIdIsNull(template.getId());
        saveTemplateAssists(course.getId(), null, templateAssists);
    }

    private void saveCourseChapters(String token, String userId, String courseId, Long parentId, List<TemplateChapter> templateChapters) {
        if (!templateChapters.isEmpty()) {
            for (TemplateChapter item : templateChapters) {
                CourseChapter chapter = new CourseChapter();
                BeanUtils.copyProperties(item, chapter);
                chapter.setId(null);
                chapter.setCourseId(courseId);
                chapter.setChildrens(null);
                chapter.setIsHide(false);
                chapter.setParentId(parentId);
                chapter = courseChapterRepository.save(chapter);
                if (chapter.getIsExp() != null && chapter.getIsExp() && !StringUtils.isEmpty(chapter.getVmName())) {
                    saveVM(token, userId, courseId, chapter.getId(), chapter.getVmName(), chapter.getVmNum());
                }
                List<TemplateChapterFile> templateChapterFiles = templateChapterFileRepository.findByChapterIdOrderByNo(item.getId());
                if (!templateChapterFiles.isEmpty()) {
                    List<CourseChapterFile> chapterFiles = new ArrayList<>();
                    for (TemplateChapterFile file : templateChapterFiles) {
                        CourseChapterFile chapterFile = new CourseChapterFile();
                        BeanUtils.copyProperties(file, chapterFile);
                        chapterFile.setId(null);
                        chapterFile.setChapterId(chapter.getId());
                        chapterFile.setIsHide(false);
                        chapterFiles.add(chapterFile);
                    }
                    courseChapterFileRepository.save(chapterFiles);
                }
                if (item.getChildrens() != null && !item.getChildrens().isEmpty()) {
                    saveCourseChapters(token, userId, courseId, chapter.getId(), item.getChildrens());
                }
            }
        }
    }

    private void saveVM(String token, String userId, String courseId, Long chapterId, String vmName, Integer vmNum) {
//        ChapterImagesDTO dto = new ChapterImagesDTO();
        ChapterImages chapterImages = new ChapterImages();
        chapterImages.setId(UUID.randomUUID().toString());
        chapterImages.setUserId(Long.parseLong(userId));
        chapterImages.setChapterId(chapterId);
        chapterImages.setImageName(vmName);
        chapterImages.setCourseId(courseId);
        chapterImages.setNum(1);
        if (vmNum!=null){
            chapterImages.setNum(vmNum);
        }
        chapterImages.setCreateDate(new Date());
        chapterImagesRepository.save(chapterImages);
//        dto.setUserId(userId);
//        dto.setCourseId(courseId);
//        dto.setChpaterId(chapterId.toString());
//        dto.setImageId(vmId);
//        dto.setNum(vmNum);
//        rdsClient.saveVM(token, dto);
    }

    private void saveTemplateAssists(String courseId, Long parentId, List<TemplateAssist> templateAssists) {
        if (!templateAssists.isEmpty()) {
            for (TemplateAssist item : templateAssists) {
                CourseAssist assist = new CourseAssist();
                BeanUtils.copyProperties(item, assist);
                assist.setId(null);
                assist.setCourseId(courseId);
                assist.setParentId(parentId);
                assist.setIsHide(false);
                assist = courseAssistRepository.save(assist);
                List<TemplateAssist> itemAssists = templateAssistRepository.findByParentId(item.getId());
                if (!itemAssists.isEmpty()) {
                    saveTemplateAssists(courseId, assist.getId(), itemAssists);
                }
            }
        }
    }
}
